/*
 * @FilePath: /api-gen/src/utils/request.js
 * @Author: 张文鑫
 * @Date: 2025-03-03 18:39:24
 * @Description:
 */
import axios from "axios";

const service = axios.create({
  baseURL: process.env.API_BASE_URL,
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在这里统一添加 header
    config.headers = {
      ...config.headers,
      Authorization: "Bearer xxx", // 例如添加认证 token
      "Content-Type": "application/json",
      // 其他通用 header
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const request = {
  get: (config) => service({ ...config, method: "get" }),
  post: (config) => service({ ...config, method: "post" }),
  put: (config) => service({ ...config, method: "put" }),
  delete: (config) => service({ ...config, method: "delete" }),
  upload: (config) => {
    const formData = new FormData();
    if (config.file) {
      formData.append("file", config.file);
    }
    if (config.data) {
      Object.keys(config.data).forEach((key) => {
        formData.append(key, config.data[key]);
      });
    }
    return service({
      ...config,
      method: "post",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      data: formData,
    });
  },
  download: (config) => {
    return service({
      ...config,
      method: "get",
      responseType: "blob",
    }).then((response) => {
      const blob = new Blob([response]);
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = config.filename || "download";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    });
  },
};

export default request;
